﻿using Pay.Dal;
using Pay.Dapper;
using Pay.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Pay.Model;
using Dapper.Contrib.Extensions;
using Pay.Model.Interfaces;
using Pay.Model.Enums;

namespace Pay.DalImplement
{
    public class PayDal : IPayDal
    {
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<long> CreateOrder(OrderInfo model)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                await conn.InsertAsync(model);
                return model.Id;
            }
        }

        /// <summary>
        /// 根据商户编号获取API信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<MerchantInfo> GetMerchantByCode(string code)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                var sql = "select TOP(1) Id,AppId,AccessKey,MerchantCode,FeeRate,ExpireTime,CreateTime from merchant_info where MerchantCode = @MerchantCode";
                return await conn.QueryFirstOrDefaultAsync<MerchantInfo>(sql, new { MerchantCode = code });
            }
        }

        /// <summary>
        /// 获取平台订单信息
        /// </summary>
        /// <param name="merchantId"></param>
        /// <param name="merchantTradeNo"></param>
        /// <returns></returns>
        public async Task<OrderInfo> GetOrderByMerchantTradeNo(long merchantId, string merchantTradeNo)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                const string sql = "SELECT TOP(1) * FROM dbo.order_info WHERE MerchantId = @merchantId AND MchTradeNo = @merchantTradeNo";
                var data = await conn.QueryFirstOrDefaultAsync<OrderInfo>(sql, new { @merchantId = merchantId, @merchantTradeNo = merchantTradeNo });
                return data;
            }
        }

        /// <summary>
        /// 获取最后一次交易信息
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public async Task<OrderInfo> GetLastOrderByMerchantId(long merchantId)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                const string sql = "SELECT TOP(1) * FROM dbo.order_info WHERE MerchantId = @merchantId ORDER BY Id DESC";
                var data = await conn.QueryFirstOrDefaultAsync<OrderInfo>(sql, new { @merchantId = merchantId });
                return data;
            }
        }



        /// <summary>
        /// 获取该商户订单
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public async Task<IPagedOutput<OrderInfo>> GetOrders(int offset, int rows,
            long? merchantId = null, bool? isCompleted = null, PayType? payType = null, AlipayOrderStatus? payStatus = null,
            string orderAlipayAccount = null, string orderSystemAccount = null,
            string mchTradeNo = null, decimal? amount = null, decimal? amountPay = null)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                var param = new DynamicParameters();
                StringBuilder sql = new StringBuilder("SELECT * FROM dbo.order_info WHERE 1 = 1 ");
                if (merchantId.HasValue)
                {
                    sql.Append(" AND MerchantId = @merchantId ");
                    param.Add("merchantId", merchantId);
                }

                if (isCompleted.HasValue)
                {
                    sql.Append(" AND IsCompleted = @isCompleted ");
                    param.Add("isCompleted", isCompleted);
                }

                if (payType.HasValue)
                {
                    sql.Append(" AND PayType = @payType ");
                    param.Add("payType", payType);
                }

                if(payStatus.HasValue)
                {
                    sql.Append(" AND PayStatus = @payStatus ");
                    param.Add("payStatus", payStatus);
                }

                if (!string.IsNullOrWhiteSpace(orderAlipayAccount))
                {
                    sql.Append(" AND OrderAlipayAccount = @orderAlipayAccount ");
                    param.Add("orderAlipayAccount", orderAlipayAccount);
                }

                if (!string.IsNullOrWhiteSpace(orderSystemAccount))
                {
                    sql.Append(" AND OrderSystemAccount = @orderSystemAccount ");
                    param.Add("orderSystemAccount", orderSystemAccount);
                }

                if (!string.IsNullOrWhiteSpace(mchTradeNo))
                {
                    sql.Append(" AND MchTradeNo = @mchTradeNo ");
                    param.Add("mchTradeNo", mchTradeNo);
                }

                if (amount.HasValue)
                {
                    sql.Append(" AND Amount = @amount ");
                    param.Add("amount", amount);
                }

                if(amountPay.HasValue)
                {
                    sql.Append(" AND AmountPay = @amountPay ");
                    param.Add("amountPay", amountPay);
                }

                var data = await conn.PagedByAsync<OrderInfo>(sql, param, offset, rows);
                return data;
            }
        }

        /// <summary>
        /// 根据merchantId获取关联的支付宝账号
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public async Task<List<AliAccountInfo>> GetAlipayAccountByMerchantId(long merchantId, bool isEnable, DateTime activeTime)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                // 正序排序
                var sql = "SELECT * FROM dbo.aliaccount_info WHERE [MerchantId] = @merchantId AND IsEnable = @isEnable AND ActiveTime >= @activeTime ORDER BY Id ASC";
                var data = await conn.QueryAsync<AliAccountInfo>(sql, new { @merchantId = merchantId, @isEnable = isEnable, @activeTime = activeTime });
                return data.ToList();
            }
        }

        /// <summary>
        /// 根据支付宝账号和总金额获取二维码信息
        /// </summary>
        /// <param name="merchantId"></param>
        /// <param name="alipayAccountId"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public async Task<IPagedOutput<QRCodeInfo>> GetQrcodes(int offset, int rows, long[] aliAccountId = null, decimal? amount = null, string description = null)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                DynamicParameters param = new DynamicParameters();
                StringBuilder sql = new StringBuilder("SELECT * FROM dbo.qrcode_info WHERE 1 = 1 ");

                if (aliAccountId != null && aliAccountId.Length > 0)
                {
                    sql.Append(" AND AliAccountId in @aliAccountId ");
                    param.Add("aliAccountId", aliAccountId);
                }

                if (amount.HasValue)
                {
                    sql.Append(" AND Amount = @amount ");
                    param.Add("amount", amount);
                }

                if (!string.IsNullOrWhiteSpace(description))
                {
                    sql.Append(" AND Ddescription = @description ");
                    param.Add("description", description);
                }

                var data = await conn.PagedByAsync<QRCodeInfo>(sql, param, offset, rows);
                return data;
            }
        }
    }
}